package com.tiktok.controller;

import lombok.extern.slf4j.Slf4j;
import org.springframework.core.io.FileSystemResource;
import org.springframework.core.io.Resource;
import org.springframework.http.HttpHeaders;
import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;

import java.io.File;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;

/**
 * 文件访问控制器
 */
@RestController
@RequestMapping("/files")
@Slf4j
public class FileAccessController {

    // 视频存储路径
    private static final String VIDEO_PATH = "D:\\api_homework\\tiktok_videos";
    // 图片存储路径  
    private static final String IMAGE_PATH = "D:\\api_homework\\tiktok_images";
    // 用户头像存储路径
    private static final String AVATAR_PATH = "D:\\api_homework\\tiktok_user_photo";

    /**
     * 访问视频文件
     */
    @GetMapping("/video/**")
    public ResponseEntity<Resource> getVideo(@RequestParam String path) {
        try {
            // 从请求路径中提取文件路径
            String filePath = path.replace("/api/files/video/", "");
            Path videoPath = Paths.get(VIDEO_PATH, filePath);
            
            if (!Files.exists(videoPath)) {
                return ResponseEntity.notFound().build();
            }

            Resource resource = new FileSystemResource(videoPath);
            
            // 获取文件的媒体类型
            String contentType = Files.probeContentType(videoPath);
            if (contentType == null) {
                contentType = "application/octet-stream";
            }

            return ResponseEntity.ok()
                    .contentType(MediaType.parseMediaType(contentType))
                    .header(HttpHeaders.CONTENT_DISPOSITION, "inline; filename=\"" + videoPath.getFileName() + "\"")
                    .body(resource);

        } catch (Exception e) {
            log.error("访问视频文件失败: {}", path, e);
            return ResponseEntity.internalServerError().build();
        }
    }

    /**
     * 直接通过路径访问视频文件
     */
    @GetMapping("/video/{year}/{month}/{day}/{filename}")
    public ResponseEntity<Resource> getVideoByPath(
            @PathVariable String year,
            @PathVariable String month, 
            @PathVariable String day,
            @PathVariable String filename) {
        try {
            Path videoPath = Paths.get(VIDEO_PATH, year, month, day, filename);
            
            if (!Files.exists(videoPath)) {
                log.warn("视频文件不存在: {}", videoPath);
                return ResponseEntity.notFound().build();
            }

            Resource resource = new FileSystemResource(videoPath);
            
            // 获取文件的媒体类型
            String contentType = Files.probeContentType(videoPath);
            if (contentType == null) {
                contentType = "video/mp4"; // 默认视频类型
            }

            return ResponseEntity.ok()
                    .contentType(MediaType.parseMediaType(contentType))
                    .header(HttpHeaders.CONTENT_DISPOSITION, "inline; filename=\"" + filename + "\"")
                    .header(HttpHeaders.CACHE_CONTROL, "max-age=3600")
                    .body(resource);

        } catch (Exception e) {
            log.error("访问视频文件失败: {}/{}/{}/{}", year, month, day, filename, e);
            return ResponseEntity.internalServerError().build();
        }
    }

    /**
     * 访问图片文件
     */
    @GetMapping("/image/{year}/{month}/{day}/{filename}")
    public ResponseEntity<Resource> getImageByPath(
            @PathVariable String year,
            @PathVariable String month,
            @PathVariable String day,
            @PathVariable String filename) {
        try {
            Path imagePath = Paths.get(IMAGE_PATH, year, month, day, filename);
            
            if (!Files.exists(imagePath)) {
                log.warn("图片文件不存在: {}", imagePath);
                return ResponseEntity.notFound().build();
            }

            Resource resource = new FileSystemResource(imagePath);
            
            // 获取文件的媒体类型
            String contentType = Files.probeContentType(imagePath);
            if (contentType == null) {
                contentType = "image/jpeg"; // 默认图片类型
            }

            return ResponseEntity.ok()
                    .contentType(MediaType.parseMediaType(contentType))
                    .header(HttpHeaders.CONTENT_DISPOSITION, "inline; filename=\"" + filename + "\"")
                    .header(HttpHeaders.CACHE_CONTROL, "max-age=86400") // 图片缓存24小时
                    .body(resource);

        } catch (Exception e) {
            log.error("访问图片文件失败: {}/{}/{}/{}", year, month, day, filename, e);
            return ResponseEntity.internalServerError().build();
        }
    }

    /**
     * 访问用户头像文件
     */
    @GetMapping("/avatar/{year}/{month}/{day}/{filename}")
    public ResponseEntity<Resource> getAvatarByPath(
            @PathVariable String year,
            @PathVariable String month,
            @PathVariable String day,
            @PathVariable String filename) {
        try {
            Path avatarPath = Paths.get(AVATAR_PATH, year, month, day, filename);
            
            if (!Files.exists(avatarPath)) {
                log.warn("头像文件不存在: {}", avatarPath);
                return ResponseEntity.notFound().build();
            }

            Resource resource = new FileSystemResource(avatarPath);
            
            // 获取文件的媒体类型
            String contentType = Files.probeContentType(avatarPath);
            if (contentType == null) {
                contentType = "image/jpeg"; // 默认图片类型
            }

            return ResponseEntity.ok()
                    .contentType(MediaType.parseMediaType(contentType))
                    .header(HttpHeaders.CONTENT_DISPOSITION, "inline; filename=\"" + filename + "\"")
                    .header(HttpHeaders.CACHE_CONTROL, "max-age=86400") // 头像缓存24小时
                    .body(resource);

        } catch (Exception e) {
            log.error("访问头像文件失败: {}/{}/{}/{}", year, month, day, filename, e);
            return ResponseEntity.internalServerError().build();
        }
    }

    /**
     * 获取文件信息
     */
    @GetMapping("/info/video/{year}/{month}/{day}/{filename}")
    public ResponseEntity<Object> getVideoInfo(
            @PathVariable String year,
            @PathVariable String month,
            @PathVariable String day,
            @PathVariable String filename) {
        try {
            Path videoPath = Paths.get(VIDEO_PATH, year, month, day, filename);
            
            if (!Files.exists(videoPath)) {
                return ResponseEntity.notFound().build();
            }

            File file = videoPath.toFile();
            
            return ResponseEntity.ok()
                    .body(new Object() {
                        public String name = filename;
                        public long size = file.length();
                        public long lastModified = file.lastModified();
                        public String path = videoPath.toString();
                    });

        } catch (Exception e) {
            log.error("获取视频文件信息失败: {}/{}/{}/{}", year, month, day, filename, e);
            return ResponseEntity.internalServerError().build();
        }
    }

    /**
     * 获取头像文件信息
     */
    @GetMapping("/info/avatar/{year}/{month}/{day}/{filename}")
    public ResponseEntity<Object> getAvatarInfo(
            @PathVariable String year,
            @PathVariable String month,
            @PathVariable String day,
            @PathVariable String filename) {
        try {
            Path avatarPath = Paths.get(AVATAR_PATH, year, month, day, filename);
            
            if (!Files.exists(avatarPath)) {
                return ResponseEntity.notFound().build();
            }

            File file = avatarPath.toFile();
            
            return ResponseEntity.ok()
                    .body(new Object() {
                        public String name = filename;
                        public long size = file.length();
                        public long lastModified = file.lastModified();
                        public String path = avatarPath.toString();
                        public String type = "avatar";
                    });

        } catch (Exception e) {
            log.error("获取头像文件信息失败: {}/{}/{}/{}", year, month, day, filename, e);
            return ResponseEntity.internalServerError().build();
        }
    }
} 